const mongoose = require("mongoose");
const TestQues = require("../models/testQuesModel");

//增加试题
exports.createTestQues = async (req, res) => {
  try {
    const newTestQues = await TestQues.create(req.body);
    // 201 Created 已创建
    res.status(201).json({
      status: "success",
      data: newTestQues,
    });
  } catch (err) {
    console.log("添加试题失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//删除试题
exports.deleteTestQues = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const data = await TestQues.deleteOne({ _id: id });
    res.status(200).json({
      status: "success",
      data: data,
    });
  } catch (err) {
    console.log("删除试题失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//修改试题
exports.updateTestQues = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const newTestQues = await TestQues.findByIdAndUpdate(id, req.body, {
      new: true,
    });
    if (!newTestQues) {
      return res.status(404).json({
        message: "修改的试题并不存在",
      });
    }
    res.status(200).json({
      status: "success",
      data: newTestQues,
    });
  } catch (err) {
    console.log("修改试题失败", err);
    res.status(404).json({
      err,
    });
  }
};

//获取所有试题
exports.getAllTestQues = async (req, res) => {
  try {
    const testQuesList = await TestQues.find();
    res.status(200).json({
      status: "success",
      data: testQuesList,
    });
  } catch (err) {
    console.log("获取所有试题失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};
